<template>
<my-tree :tree.sync="rootDev"></my-tree>
</template>

<script>
import _ from 'lodash'
import ebus from 'libs/ebus.js'
import toast from 'libs/toast.js'
import {printObj} from 'libs/utils.js'
import {mediaApi, streamSrcApi} from 'share/server/api.js'
import {
  doLoadMtSrcs,
} from 'share/server/vuex/actions/streamsrc.js'

const g_pageCount = 200

export default {
  vuex: {
    getters: {
      mtsrcs: (state) => state.mtsrc.list
    },
    actions: {
      doLoadMtSrcs
    }
  },
  data () {
    return {
      show: false,
      rootDev: {
        name: '',
        icon: 'octicon octicon-server',
        open: false,
        loading: false,
        isFolder: true, 
        getChilds: this.getDevsOfTreeNode,
        totalCount: 0,
        startIndex: 0,
        childs: [],
        actions: [{
          name: this.$t('common.nextPage'),
          doClick: this.getNextPageDevsOfTreeNode,
          type: 'info',
          isShow: this.isPageActionShow,
          isEnable: this.isNextPageActionEnable
        }, {
          name: this.$t('common.prevPage'),
          doClick: this.getPrevPageDevsOfTreeNode,
          type: 'info',
          isShow: this.isPageActionShow,
          isEnable: this.isPrevPageActionEnable
        }, {
          name: this.$t('common.refresh'),
          doClick: this.getDevsOfTreeNode,
          type: 'info',
          isShow: this.isRefreshActionShow
        }],
        usrCfg: null
      }
    }
  },
  methods: {
    getMtsrcWithDeviceId (monitorId, deviceId) {
      let mtsrc = _.find(this.mtsrcs, (item) => {
        if (item.monitorOfId != monitorId
          || item.srcDeviceId != deviceId) {
          return false
        } else {
          return true
        }
      })

      return mtsrc
    },
    isFolderDev (devType) {
      //return ['nvr', 'dvr'].includes(devType)
      return _.includes(['nvr', 'dvr'], devType)
    },
    isRefreshActionShow (tree) {
      return !tree.open || tree.totalCount <= g_pageCount
    },
    isPageActionShow (tree) {
      return tree.open && tree.totalCount > g_pageCount
    },
    isPrevPageActionEnable (tree) {
      return (tree.startIndex - g_pageCount) >= 0
    },
    isNextPageActionEnable (tree) {
      return (tree.startIndex + g_pageCount) <= tree.totalCount
    },
    insertFolderDev (tree, device) {
      tree.childs.splice(tree.childs.length, 0, {
        name: device.name,
        icon: 'octicon octicon-server',
        open: false,
        loading: false,
        isFolder: true, 
        getChilds: this.getDevsOfTreeNode,
        totalCount: device.childTotalCount,
        startIndex: 0,
        childs: [],
        father: tree,
        actions: [{
          name: this.$t('common.nextPage'),
          doClick: this.getNextPageDevsOfTreeNode,
          type: 'info',
          isShow: this.isPageActionShow,
          isEnable: this.isNextPageActionEnable
        }, {
          name: this.$t('common.prevPage'),
          doClick: this.getPrevPageDevsOfTreeNode,
          type: 'info',
          isShow: this.isPageActionShow,
          isEnable: this.isPrevPageActionEnable
        }, {
          name: this.$t('common.refresh'),
          doClick: this.getDevsOfTreeNode,
          type: 'info',
          isShow: this.isRefreshActionShow
        }],
        usrCfg: device             
      })
    },
    initMtsrcActionWithConnect (action) {
      action.name = this.$t('common.connect')
      action.doClick = this.mtsrcConnect
      action.type = 'primary'
    },
    initMtsrcActionWithDisconnect (action) {
      action.name = this.$t('common.disconnect')
      action.doClick = this.mtsrcDisconnect
      action.type = 'danger'
    },
    mtsrcConnect (tree) {
      var device = tree.usrCfg
      var monitor = device.monitor
      var mtsrc = {
        name: device.name,
        tag: '',
        monitorOfId: monitor._id,
        deviceOfName: device.name,
        topoIdOfMediaDev: monitor.topoIdOfMediaDev,
        srcDeviceId: device.deviceId
      }

      tree.loading = true
      streamSrcApi.setItem('mtsrcs', mtsrc).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          this.doLoadMtSrcs()
          this.initMtsrcActionWithDisconnect(tree.actions.mtsrc)
          this.sortTree(tree.father)
        } else {
          toast.code(this, res.data)
        }

        tree.loading = false
      }.bind(this))
    },
    mtsrcDisconnect (tree) {
      var device = tree.usrCfg
      var monitor = device.monitor
      var mtsrc = this.getMtsrcWithDeviceId(monitor._id, device.deviceId)
      if (!mtsrc) {
        return
      }

      tree.loading = true
      streamSrcApi.delItem('mtsrcs', mtsrc._id).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          this.doLoadMtSrcs()
          this.initMtsrcActionWithConnect(tree.actions.mtsrc)
          this.sortTree(tree.father)
        } else {
          toast.code(this, res.data)
        }

        tree.loading = false
      }.bind(this))
    },
    insertNormalDev (monitorId, tree, device) {
      let mtsrc = this.getMtsrcWithDeviceId(monitorId, device.deviceId)
      var action = {}

      if (mtsrc) {
        this.initMtsrcActionWithDisconnect(action)
      } else {
        this.initMtsrcActionWithConnect(action)
      }

      tree.childs.splice(tree.childs.length, 0, {
        name: device.name,
        icon: 'octicon octicon-device-camera-video',
        open: false,
        loading: false,
        isFolder: false,
        father: tree, 
        actions:{
          mtsrc: action
        },
        usrCfg: device             
      })
    },
    insertDev (monitorId, tree, device) {
      if (this.isFolderDev(device.devType)) {
        this.insertFolderDev(tree, device)
      } else {
        this.insertNormalDev(monitorId, tree, device)
      }
    },
    sortTree (tree) {
      let childs = _.orderBy(tree.childs, ['isFolder', 'actions.mtsrc.name', 'name'], ['desc', 'asc', 'asc'])
      tree.childs = childs
    },
    getDevsOfTreeNodeWithOpt (tree, opt) {
      var usrCfg = tree.usrCfg
      var monitor = usrCfg.monitor ? usrCfg.monitor : usrCfg

      tree.loading = true

      var req = {
        topoIdOfMediaDev: monitor.topoIdOfMediaDev,
        monitorName: monitor.name,
        startIndex: opt.startIndex,
        pageCount: g_pageCount
      }
      if (monitor != usrCfg) {
        req.deviceId = usrCfg.deviceId
        //console.log(usrCfg.deviceId)
        //console.log(usrCfg.nodeId)
        if (!_.isNil(usrCfg.nodeId)) {
          req.deviceId = usrCfg.nodeId
        }
      }
      mediaApi.sendCmd('getDevicesOfMonitor', req).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          var devicesOfMonitor = res.data.data.devicesOfMonitor
          tree.childs.splice(0, tree.childs.length)
          tree.totalCount = res.data.data.totalCount
          tree.startIndex = req.startIndex
          for (var i = 0; i < devicesOfMonitor.length; i++) {
            var device = devicesOfMonitor[i]
            device.monitor = monitor
            this.insertDev(monitor._id, tree, device)
          }
          this.sortTree(tree)
          tree.open = true
        }

        tree.loading = false
      }.bind(this))
    },
    getDevsOfTreeNode (tree) {
      this.doLoadMtSrcs()
      this.getDevsOfTreeNodeWithOpt(tree, {
        startIndex: 0
      })
    },
    getPrevPageDevsOfTreeNode (tree) {
      this.getDevsOfTreeNodeWithOpt(tree, {
        startIndex: tree.startIndex - g_pageCount
      })
    },
    getNextPageDevsOfTreeNode (tree) {
      this.getDevsOfTreeNodeWithOpt(tree, {
        startIndex: tree.startIndex + g_pageCount
      })
    },
    updateRootDev (currMonitor) {
      var rootDev = this.rootDev
      let monitor = rootDev.usrCfg

      if ((rootDev.name !== currMonitor.name)
        || (monitor === null)
        || (monitor._id !== currMonitor._id)
        || (monitor.vendor !== currMonitor.vendor)) {
        rootDev.name = currMonitor.name
        rootDev.usrCfg = currMonitor
        this.getDevsOfTreeNode(rootDev)
      }
    },
    disconnectAll () {
      var rootDev = this.rootDev
      let monitor = rootDev.usrCfg

      mediaApi.sendCmd('delAllSrcOfMonitor', {monitorId: monitor._id}).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          this.doLoadMtSrcs()
          this.getDevsOfTreeNode(rootDev)
        } else {
          toast.code(this, res.data)
        }
      }.bind(this))
    }
  },
  ready () {
    ebus.on('monitor-tree-update', this.updateRootDev)
    ebus.on('del-all-monitor-src', this.disconnectAll)
  }
}
</script>

<style>
</style>